﻿using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Sustainalytics.Claims;
using Sustainalytics.DataLayer.Shared;
using Sustainalytics.ESG.Entities;
using Sustainalytics.ESGRatings.BusinessLogic.ESGOnlineReport;
using Sustainalytics.ESGRatings.Service.Models.Common;
using Sustainalytics.Utils;
using Sustainalytics.Utils.WebApi.ErrorCodes;
using Sustainalytics.DataLayer.EsgRatings;
using System.Web.Http.Cors;

namespace Sustainalytics.ESGRatings.Service
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [ClaimsChecker("api/v1/esgRpIndicatorCluster")]
    [RoutePrefix("api/v1/esgRpIndicatorCluster")]
    //[AutoInvalidateCacheOutput]
    [LogControllerFilter(true, true, false)]
    public class EsgRpIndicatorClusterController : ApiController
    {


          public EsgRpIndicatorClusterController()
        {
            Setup();
        }

          public EsgRpIndicatorClusterController(IOnlineResearchProductsBusinessLogicUnit service)
        {
            _service = service;
        }


        // [CacheOutput(ServerTimeSpan = 100, ClientTimeSpan = 0, NoCache = true, MustRevalidate = true, Private = true)]
        [Route("")]
          public HttpResponseMessage Get([FromUri]EsgThemeEnum theme)
        {
            try
            {
                var data = _service.GetIndicatorsClusters(theme.ToString()).Select(x => new { Id = x.Item1, Name = x.Item2 });

                return Request.CreateResponse(HttpStatusCode.OK, data);
            }
            catch (ESGReasearchNotFoundException ex)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound, new
                {
                    errCode = ex.GetType().ToString(),
                    message = ex.Message
                });

            }
            catch (ESGReasearchNotInUniversesException ex)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound, new
                {
                    errCode = ex.GetType().ToString(),
                    message = ex.Message
                });

            }
            catch (Exception ex)
            {
                CommonEventSource.Log.Exception(ex);
                return this.Request.CreateResponse(HttpStatusCode.InternalServerError,
                    new { ErrorStatusCode = WebAPIGeneralErrorCodes.UnhandledException });
            }
        }

      


        private IOnlineResearchProductsBusinessLogicUnit _service;


        private void Setup()
        {

            IRepositoryCollection<IndicatorTemplate> repository =
                new RPIndicatorsRepository<IndicatorTemplate>(ClientDWConnection.GetConnectionString());

            _service = _service ?? new OnlineResearchProductsBusinessLogicUnit(repository);
        }
    }
}
